import { defineStore } from 'pinia'
import { login, logout, getUserInfo, updateUserProfile } from '@/api/user'
import { getToken, setToken, removeToken, setUserInfo, removeUserInfo, getUserInfo as getStoredUserInfo } from '@/utils/auth'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: getToken(),
    name: '',
    userId: null,
    avatar: '',
    roles: [],
    userInfo: null
  }),
  
  getters: {
    isAdmin: (state) => state.roles.includes('admin')
  },
  
  actions: {
    // 用户登录
    async login(userInfo) {
      const { username, password } = userInfo
      try {
        const response = await login({ username: username.trim(), password })
        // 适配新的统一响应格式
        if (response.code === 200 && response.data) {
          const { access_token } = response.data
          this.token = access_token
          setToken(access_token)
        } else {
          throw new Error(response.message || '登录失败')
        }
        return response
      } catch (error) {
        console.error('Login failed:', error)
        throw error
      }
    },
    
    // 获取用户信息
    async getInfo() {
      // 优先从本地存储获取用户信息
      const storedInfo = getStoredUserInfo()
      if (storedInfo) {
        this.name = storedInfo.name || storedInfo.real_name || '';
        this.userId = storedInfo.id;
        this.roles = storedInfo.roles || [];
        this.userInfo = storedInfo;
        return storedInfo;
      }
      
      try {
        const response = await getUserInfo()
        // 适配统一响应格式
        if (response.code !== 200 || !response.data) {
          throw new Error(response.message || '获取用户信息失败，请重新登录')
        }
        
        const userData = response.data
        const { real_name, id, role } = userData
        
        // 转换角色信息
        let roles = []
        if (role === 1) {
          roles = ['admin']
        } else {
          roles = ['user']
        }
        
        this.name = real_name || userData.name || '';
        this.userId = id;
        this.roles = roles;
        
        // 保存用户信息到本地存储并更新state
        const userInfo = { ...userData, roles, name: real_name || userData.name || '' };
        this.userInfo = userInfo;
        setUserInfo(userInfo);
        return userInfo;
      } catch (error) {
        console.error('Get user info failed:', error)
        throw error
      }
    },
    
    // 用户登出
    async logout() {
      try {
        const response = await logout()
        // 适配统一响应格式
        if (response.code !== 200) {
          console.warn('登出返回状态异常:', response.message)
        }
        this.resetToken()
        removeUserInfo()
        return true
      } catch (error) {
        console.error('Logout failed:', error)
        // 即使后端登出失败，也要清除前端状态
        this.resetToken()
        removeUserInfo()
        throw error
      }
    },
    
    // 重置令牌
    resetToken() {
      this.token = ''
      this.name = ''
      this.userId = null
      this.roles = []
      this.userInfo = null
      removeToken()
      removeUserInfo()
    },
    
    // 更新用户个人资料
    async updateProfile(profileData) {
      try {
        // 确保有用户ID
        if (!this.userId) {
          throw new Error('用户ID不存在，请先登录')
        }
        
        // 构建更新数据
        const updateData = {
          ...profileData,
          id: this.userId,
          version: this.userInfo?.version || 0 // 乐观锁版本号
        }
        
        const response = await updateUserProfile(updateData)
        
        if (response.code !== 200 || !response.data) {
          throw new Error(response.message || '更新个人资料失败')
        }
        
        // 更新本地存储和状态
        const updatedUser = response.data
        const roles = updatedUser.role === 1 ? ['admin'] : ['user']
        
        const userInfo = { 
          ...updatedUser, 
          roles,
          name: updatedUser.real_name || updatedUser.user_name || '' 
        }
        
        this.name = userInfo.name
        this.userInfo = userInfo
        setUserInfo(userInfo)
        
        return userInfo
      } catch (error) {
        console.error('Update profile failed:', error)
        throw error
      }
    }
  }
})